package com.yvon.maple.service.auth.valicode.vo;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * 验证码
 *
 * @author : Yvon
 * @since : 2021-08-12
 */
public class CodeVo implements Serializable {

    /**
     * 验证码
     */
    private String code;

    /**
     * 到期时间
     */
    @JsonFormat(pattern = DatePattern.NORM_DATETIME_PATTERN)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    private LocalDateTime expireTime;

    private String key;

    private String grantType;

    public CodeVo() {
    }

    public CodeVo(String code, long expire){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expire);
    }

    public CodeVo(String code, long expire, String key){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expire);
        this.key = key;
    }

    public CodeVo(String code, long expire, String key, String grantType){
        this.code = code;
        this.expireTime = LocalDateTime.now().plusSeconds(expire);
        this.key = key;
        this.grantType = grantType;
    }



    /**
     * 是否到期
     *
     * @return boolean
     * @author : Yvon / 2021-08-12
     */
    @JsonIgnore
    public boolean isExpire() {
        return LocalDateTime.now().isAfter(expireTime);
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public LocalDateTime getExpireTime() {
        return expireTime;
    }

    public void setGrantType(String grantType) {
        this.grantType = grantType;
    }

    public String getGrantType(){
        return grantType;
    }

    public Long getExpire() {
        return LocalDateTimeUtil.between(LocalDateTime.now(), this.expireTime, ChronoUnit.SECONDS);
    }

    public void setExpireTime(LocalDateTime expireTime) {
        this.expireTime = expireTime;
    }
}
